<template>
    <div>
        <!-- 导入表 -->
        <el-dialog  :close-on-click-modal="false"  title="初始化表" :visible.sync="visible" width="100%" top="5vh" append-to-body>
            <!-- input输入框 回车触发绑定事件失效,变成刷新页面,在 form中增加 @submit.native.prevent 即可 -->

            <el-form  :model="queryParams" ref="queryForm" :inline="true" @submit.native.prevent>
                <el-form-item label="表名称" prop="searchValueListSearch">
                    <el-input
                        v-model="queryParams.searchValueListSearch"
                        placeholder="请输入表名称"
                        clearable
                        size="small"
                        @keyup.enter.native="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="过滤" prop="lookupBitFilter">
<!--                    <el-select v-model="queryParams.lookupBitFilter" placeholder="请选择" clearable size="small" style="width: 240px" >-->
<!--                        <el-option v-for="item in lookupBitFilterOptions" :key="item.value" :label="item.label" :value="item.value" />-->
<!--                    </el-select>-->
                    <SelectMultipleToBitValue :bitValueOptionList="lookupBitFilterOptions"
                                              v-model="queryParams.lookupBitFilter"
                    ></SelectMultipleToBitValue>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                    <el-button type="danger"  icon="el-icon-refresh" size="mini" @click="handleInitTableToVersion(true)">重建表版本信息</el-button>
                </el-form-item>
            </el-form>
            <el-row>
                <el-row :gutter="10" class="mb8">
                    <div class="top-right-btn">
                        <el-row>
                            <el-tooltip class="item" effect="dark" :content="showAllColumn ? '隐藏多余列' : '显示所有列'" placement="top">
                                <el-button size="mini" :type="showAllColumn?'success':'info'" circle icon="el-icon-menu" @click="showAllColumn=!showAllColumn" />
                            </el-tooltip>
                            <el-tooltip class="item" effect="dark" content="刷新" placement="top">
                                <el-button size="mini" circle icon="el-icon-refresh" @click="getList()" />
                            </el-tooltip>
                        </el-row>
                    </div>
                </el-row>
                <el-table @row-click="clickRow" ref="table" :data="initTableList" @selection-change="handleSelectionChange" height="560px">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column prop="name" label="表名称" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <el-button type="text"
                                       size="small"
                                       @click="handleShowBeanSource(scope.row)"
                            >{{scope.row.name}}</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column prop="comment" label="表描述" :show-overflow-tooltip="true"></el-table-column>
                    <el-table-column prop="defaultCharset" label="默认字符串"></el-table-column>
                    <el-table-column prop="engine" label="存储引擎"></el-table-column>
                    <el-table-column prop="indexJson" label="索引" align="center">
                        <template slot-scope="scope">
                            <div v-for="(tableIndexInfo,index) in scope.row.indexJson" class="tableIndexInfo.indexName">
                                <div class="tableColumnLineDiv">
                                    {{tableIndexInfo.indexName}}
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="triggerJson" label="触发器" align="center">
                        <template slot-scope="scope">
                            <div v-for="(triggerInfo,index) in scope.row.triggerJson" class="triggerInfo.triggerName">
                                <div class="tableColumnLineDiv">
                                    {{triggerInfo.triggerName}}
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        v-if="showAllColumn"
                                     prop="lastMd5" label="最后一次更新MD5" width="270"></el-table-column>
                    <el-table-column
                        v-if="showAllColumn"
                        prop="currentMd5" label="当前MD5" width="270"></el-table-column>
                    <el-table-column prop="updateTime" label="更新时间">
                        <template slot-scope="scope">
                            <span>{{ parseTime(scope.row.updateTime) }}</span>
                        </template>
                    </el-table-column>

                </el-table>
                <pagination
                    v-show="total>0"
                    :total="total"
                    :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize"
                    :page-sizes="[5,10, 20, 30, 50]"
                    @pagination="getList"
                />

            </el-row>
            <el-row>
                <div>
                    初始化表时如果有新索引,触发器则会新增,但不会重建索引触发器
                </div>
                <div>
                    重建索引需要谨慎
                </div>
            </el-row>
            <div slot="footer" class="dialog-footer">
                <el-button :disabled="executing" type="danger" @click="handleInitHasConfirm(0b0010)">重建索引</el-button>
                <el-button :disabled="executing"  type="danger" @click="handleInitHasConfirm(0b0100)">重建触发器</el-button>
                <el-button :disabled="executing" type="primary" @click="handleInitTable(0b0001)">初始化表</el-button>
                <el-button :disabled="executing" @click="visible = false">取 消</el-button>
            </div>
        </el-dialog>

        <el-dialog  :close-on-click-modal="false" :title="initTable.title" :visible.sync="initTable.open" width="80%" top="5vh" append-to-body>
            <h1 v-if="initTable.errorMessage">执行异常</h1>
            <div>{{formatSql(initTable.errorMessage)}}</div>
            <h1 v-if="initTable.throwSql">执行异常sql</h1>
            <div>{{formatSql(initTable.throwSql)}}</div>
            <h1 v-if="initTable.executeSqlList.length!=0">执行的sql</h1>
            <div v-for="(executeSql,index) in initTable.executeSqlList" :key="executeSql">
                <div>{{formatSql(executeSql)}}</div>
            </div>
            <h1 v-if="initTable.errorIndexSqlList.length!=0">索引执行错误sql</h1>
            <div v-for="(errorSql,index) in initTable.errorIndexSqlList" :key="errorSql">
                <div>{{formatSql(errorSql)}}</div>
            </div>

            <h1 v-if="initTable.errorTriggerSqlList.length!=0">触发器执行错误sql</h1>
            <div v-for="(errorSql,index) in initTable.errorTriggerSqlList" :key="errorSql">
                <div>{{formatSql(errorSql)}}</div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import request from '@/utils/request'

// 初始化table
export function tableBuild(data) {
    return request({
        url: '/a/build',
        method: 'post',
        data: data
    })
}

export function getInitTableList(query) {
    return request({
        url: '/a/getInitTableList',
        method: 'post',
        data: query
    })
}

export function initTableToVersion(query) {
    return request({
        url: '/a/initTableToVersion',
        method: 'get',
        params: query
    })
}


export default {
    data() {
        return {
            executing: false,
            lookupBitFilterOptions:[
                {
                    dictValue: 0,
                    dictLabel: '全部'
                },
                {
                    dictValue: 1,
                    dictLabel: '待更新'
                },
                {
                    dictValue: 2,
                    dictLabel: '不显示表自身'
                },
            ],
            initTable:{
                throwSql:"",
                errorMessage:"",
                executeSqlList:[],
                errorIndexSqlList:[],
                errorTriggerSqlList:[],
                open: false,
                title: '执行记录'
            },
            // 遮罩层
            visible: false,
            showAllColumn: false,
            // 选中数组值
            tables: [],
            // 总条数
            total: 0,
            loading: true,
            // 表数据
            initTableList: [],
            // 查询参数
            queryParams: {
                lookupBitFilter: 3,
                pageNum: 1,
                pageSize: 10,
                searchValueListSearch: null,
            }
        };
    },
    created() {
        this.initComponents();
    },
    mounted() {
        this.initComponents();
    },
    methods: {
        initComponents(){

        },
        // 显示弹框
        show() {
            this.getList();
            this.visible = true;
        },
        clickRow(row) {
            this.$refs.table.toggleRowSelection(row);
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.tables = selection.map(item => item.name);
        },
        // 查询表数据
        getList() {
            this.queryParams.searchValueList=undefined;
            if (this.queryParams.searchValueListSearch) {
                let searchValueListSearch = this.queryParams.searchValueListSearch;
                searchValueListSearch=this.resetBlank(searchValueListSearch);
                this.queryParams.searchValueList=searchValueListSearch.split(" ")
            }
            this.loading=true
            getInitTableList(this.queryParams).then(res => {
                if (res.code === 200) {
                    this.initTableList = res.data.list;
                    this.total=res.data.total
                    this.loading=false
                }
            });
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        handleInitHasConfirm(initType){
            let msgArr=[];
            if((initType&2)){
                msgArr.push('索引')
            }
            if((initType&4)){
                msgArr.push('触发器')
            }
            var msg="是否重建"+msgArr.join(",")+"?";
            this.$confirm(msg, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "info"
            }).then(() => {
                this.handleInitTable(initType);
            }).catch((res) => {
            })
        },
        /** 初始化table操作 */
        handleInitTable(initType) {
            this.initTable.errorIndexSqlList=[];
            this.initTable.errorTriggerSqlList=[];
            this.initTable.executeSqlList=[];
            this.initTable.throwSql="";
            this.initTable.errorMessage="";
            this.executing=true;
            var data={
                tables: this.tables,
                initType: initType==undefined?0b11111111:initType
            };
            tableBuild(data).then(res=>{
                if(res.data&&res.data.errorFlag){
                    console.log("res=",res)
                    this.initTable.open=true;
                    this.initTable.throwSql=res.data.data;
                    this.initTable.errorMessage=res.msg;
                    // this.initTable.errorIndexSqlList=res.data.errorIndexSqlList;
                    // this.initTable.errorTriggerSqlList=res.data.errorTriggerSqlList;
                    // this.initTable.executeSqlList=res.data.executeSqlList;
                    this.msgSuccess(res.msg);
                }else{
                    this.initTable.open=true;
                    this.initTable.errorIndexSqlList=res.data.errorIndexSqlList;
                    this.initTable.errorTriggerSqlList=res.data.errorTriggerSqlList;
                    this.initTable.executeSqlList=res.data.executeSqlList;
                    this.msgSuccess(res.msg);
                }
                this.executing=false;
            }).catch(error=>{
                this.executing=false;
            })


            // tableBuild({ tables: this.tables.join(",") }).then(res => {
            //   this.msgSuccess(res.msg);
            //   if (res.code === 200) {
            //     this.visible = false;
            //     this.$emit("ok");
            //   }
            // });
        },
        formatSql(sql){
            // console.log("formatSql=",sql)
            if(sql != undefined){
                var str=sql.trim();
                if (str.lastIndexOf(';') == str.length - 1) {
                    return str;
                }else{
                    return str+";";
                }
            }
            return "";
        },
        handleInitTableToVersion(reset){
            var msg="是否重建表版本信息";
            this.$confirm(msg, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "info"
            }).then(() => {
                var params={
                    reset: true
                }
                initTableToVersion(params).then(response=>{
                    this.msgSuccess("成功")
                })
            }).catch((res) => {
            })
        },
        handleShowBeanSource(row){
            this.$confirm(`${row.name}<br>${row.beanSource}`,'beanSource',{
                confirmButtonText: "确定",
                type: "info",
                dangerouslyUseHTMLString: true,
            })
        }
    }
};
</script>

<style lang="scss" scoped>

.tableColumnLineDiv {
    margin:5px;
    min-width: 80px;
    float: left;
    text-align:center;
}

</style>
